<?php
/**
 * User: hunter
 * Date: 2018/6/28
 * Time: 18:21
 */
namespace App\Admin\Extensions;

use Encore\Admin\Form\Field;

class jsonEditor extends Field
{
    protected $view = 'laravel-admin.form.jsonEditor';

    protected static $css = [
        '/vendor/jsoneditor-5.16.0/dist/jsoneditor.min.css',
    ];

    protected static $js = [
        '/vendor/jsoneditor-5.16.0/dist/jsoneditor.min.js',
        '/vendor/jsoneditor-5.16.0/dist/FileReader.js',
    ];

    public function render()
    {
        $name = $this->formatName($this->column);

        $this->script = <<<EOT
  
var container = document.getElementById('jsoneditor_{$name}');
var options = {
    mode: 'code',
    modes: ['code', 'form', 'text', 'tree', 'view'], // allowed modes
    onError: function (err) {
      alert(err.toString());
    },
    onModeChange: function (newMode, oldMode) {
      console.log('Mode switched from', oldMode, 'to', newMode);
    },
    onChange: function() {
        var json = editor.get();
        $(":input[name='{$name}']").val(JSON.stringify(json));
    }
  };

if($(":input[name='{$name}']").val() !=''){
var json =  JSON.parse($(":input[name='{$name}']").val());
}else{
var json =  JSON.parse("{}");
}

var editor = new JSONEditor(container, options, json);

$('.config_file_select').on('change', function() {
        //console.log($(this).val());
        console.log(editor.get());
        var json_str = JSON.parse($(this).val());
        editor.set(json_str);
});
    
FileReaderJS.setupInput(document.getElementById('loadDocument'), {
    readAsDefault: 'Text',
    on: {
      load: function (event, file) {
        editor.setText(event.target.result);
        var json = editor.get();
        $(":input[name='{$name}']").val(JSON.stringify(json));
      }
    }
  });
EOT;
        return parent::render();
    }
}